
#include "integer.h"


unsigned long long mask = 0xffff;
static unsigned char bit1Table_16bit[65536];
static unsigned short reverseTable[65536];


void printReverseTable() {
	PRINT_FUNC_NAME;

	for(int i = 0; i < 65536; i++) {
		printf("%d, ", reverseTable[i]);
	}
	printf("\n");
}

void printBit1Table() {
	PRINT_FUNC_NAME;

	for(int i = 0; i < 65536; i++) {
		printf("%d, ", bit1Table_16bit[i]);
	}
	printf("\n");
}

void generateNumOfBit1Table() {
	PRINT_FUNC_NAME;
	
	for(unsigned int i = 0; i < 65536; i++) {
		unsigned short x = (unsigned short)i;
		bit1Table_16bit[i] = countBit1((byte*)(&x), sizeof(unsigned short));
	}
}

unsigned short reverse16bit(unsigned short x) {
	unsigned short y = 0;
	unsigned short bit = 0;

	for(int i = 0; i < 16; i++) {
		bit = x&0x1;
		x = x>>1;
		y = y|(bit<<(15 - i));
	}
	return y;
}



void generateReversionTable() {
	PRINT_FUNC_NAME;
	
	for(int i = 0; i < 65536; i++) {
		reverseTable[i] = reverse16bit(i);
	}
}

int host_popcll(unsigned long long x) {

	int n2 = 0;
#pragma unroll 4
	for(int i = 0; i < 4; i++) {
		n2 += bit1Table_16bit[x&mask];
		x = x>>16;
	}
	return n2;
}

unsigned long long host_brevll(const unsigned long long x) {
	/*use bitwise function*/
/*
	unsigned long long y = 0;
	unsigned long long bit = 0;
#pragma unroll 64
	for(int i = 0; i < 64; i++) {
		bit = x&0x1;
		x = x>>1;
		y = y|(bit<<(63 - i));
	}
	return y;
*/
	
	/*use lookup table*/
	unsigned long long y = 0;
	y = y|(((unsigned long long)reverseTable[x&0xffff])<<48);
	y = y|(((unsigned long long)reverseTable[(x&0xffff0000)>>16])<<32);
	y = y|(((unsigned long long)reverseTable[(x&0xffff00000000)>>32])<<16);
	y = y|(((unsigned long long)reverseTable[(x&0xffff000000000000)>>48]));

	return y;
}

